using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using SharePoint.Sunbox.Sandbox.Resources;

namespace SharePoint.Sunbox.Sandbox.Features.MainFeature
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    [Guid("55cfad53-ccf2-4428-a3bb-04226b586baf")]
    public class MainFeatureEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        private readonly string[] _folderUrls = { "Style Library/Sunbox" };

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var site = properties.Feature.Parent as SPSite;
            if (site != null)
            {
                SPWeb rootWeb = site.RootWeb;

                CheckInFiles(rootWeb);

                LocalizeWebPartsProperties(rootWeb);
            }
        }

        private void CheckInFiles(SPWeb rootWeb)
        {
            SPList styleLibrary = rootWeb.GetList(rootWeb.Url + "/Style Library");
            if (styleLibrary != null)
            {
                SPListItemCollection folders = styleLibrary.Folders;
                //string featureId = properties.Feature.Definition.Id.ToString();

                foreach (string folderUrl in _folderUrls)
                {
                    SPFolder folder = GetFolderByUrl(folders, folderUrl);
                    if (folder != null)
                    {
                        PublishFiles(folder);
                    }
                }
            }
        }

        private static SPFolder GetFolderByUrl(SPListItemCollection folders, string folderUrl)
        {
            if (folders == null)
            {
                throw new ArgumentNullException("folders");
            }

            if (String.IsNullOrEmpty(folderUrl))
            {
                throw new ArgumentNullException("folderUrl");
            }

            SPFolder folder = null;

            SPListItem item = (from SPListItem i
                                   in folders
                               where i.Url.Equals(folderUrl, StringComparison.InvariantCultureIgnoreCase)
                               select i).FirstOrDefault();

            if (item != null)
            {
                folder = item.Folder;
            }

            return folder;
        }

        private static void PublishFiles(SPFolder folder)
        {
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }

            SPFileCollection files = folder.Files;
            IEnumerable<SPFile> checkedOutFiles = from SPFile f
                                                      in files
                                                  where f.Level == SPFileLevel.Checkout
                                                  select f;

            foreach (SPFile f in checkedOutFiles)
            {
                f.CheckIn(String.Empty, SPCheckinType.MajorCheckIn);
            }
            if (folder.SubFolders.Count <= 0) return;

            foreach (SPFolder subFolder in folder.SubFolders)
            {
                PublishFiles(subFolder);
            }
        }

        private void LocalizeWebPartsProperties(SPWeb web)
        {
            try
            {
                LocalizeWebPart(web, "DataViewWebPart.webpart", Properties.DataViewWebPartTitle, Properties.DataViewWebPartDescription);
                LocalizeWebPart(web, "CommentsWebPart.webpart", Properties.CommentsWebPartTitle, Properties.CommentsWebPartTitle);
            }
            catch
            {
                
            }
        }

        private void LocalizeWebPart(SPWeb web, string webPartFileName, string webPartTitle, string webPartDescription)
        {
            SPList catalog = web.GetCatalog(SPListTemplateType.WebPartCatalog);

            //sunbox dataview
            var query = new SPQuery
            {
                Query =
                    string.Format(
                        @"<Where><Eq><FieldRef Name='LinkFilename'/><Value Type='Computed'>{0}</Value></Eq></Where>",
                        webPartFileName)
            };
            SPListItem webPartItem = catalog.GetItems(query).Cast<SPListItem>().FirstOrDefault();
            if (webPartItem != null)
            {
                webPartItem[SPBuiltInFieldId.Title] = webPartTitle;
                webPartItem["WebPartDescription"] = webPartDescription;
                webPartItem.Update();
            }
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}